#!/usr/bin/env python

import gtk, gobject
import gettext
from blend import constants
from signals import buddyWindowSignals, commonSignals
import constants as iconstants
from blend import const
from mxit import handles
import time

gettext.install('blendIT','locale');

class buddyWindow(gtk.Window):

   expands = {};

   def __init__(self,blend):
      gtk.Window.__init__(self,gtk.WINDOW_TOPLEVEL);
      self.set_title(_("BlendIt Buddies"));
      self.set_geometry_hints(min_width=100, min_height=100);
      self.set_default_size(240,600); # TO DO - Persistant GUI Dimensions
      self.set_icon_from_file("images/blendit.png");


      accel_group = gtk.AccelGroup();
      self.sigs = buddyWindowSignals.signals(blend);
      self.csigs = commonSignals.signals(blend);
      self.connect('delete_event',self.sigs.close,True);
      self.blend = blend;
      
      # The window contains a bunch of stuff:
      menu = self.drawMenuBar(accel_group);
      scrolledTree = self.drawScrolledTreeView();
      statusBox = self.drawStatusBar();
      
      # Create a vbox for this stuff to get put into:
      vbox = gtk.VBox();
      vbox.pack_start(menu,False,False);
      vbox.pack_start(scrolledTree,True,True);
      vbox.pack_end(statusBox,False,False);
      vbox.show();

      self.add(vbox);
      self.add_accel_group(accel_group);

   ### Methods ###
   def addGroup(self,group):
      noImg = gtk.gdk.pixbuf_new_from_file_at_size(iconstants.IMG_Blank,16,16);
      tooltip = self.makeTooltipString(group,type=const.GROUP);
      data = (noImg,"<b>" + group.real_name + "</b>",None,
              False,tooltip,const.GROUP,"");

      return self.model.get_model().append(None,data);

   ## This checks if a group is expanded and stores the info
   def rememberExpands(self):
      # Go through each parent iter. get it's path. Store it. Be happy
      iter = self.model.get_model().get_iter_first();
      while iter != None:
         name = self.model.get_model().get_value(iter,1).replace("<b>","").replace("</b>","");
         path = self.model.get_model().get_path(iter);

         self.expands[name] = (self.tree.row_expanded(path),path);

         iter = self.model.get_model().iter_next(iter);

   # Check to see if we have info about a group stored. If we do, see if it
   # must be expanded or not.
   def recallExpand(self,group,force=False):
      if self.expands.has_key(str(group.real_name)):

         # Get the state
         state = self.expands[str(group.real_name)][0];
         path = self.expands[str(group.real_name)][1];
         if force == True:
            state = True;
         if state == True:
            # Expand
            self.tree.expand_row(path,True);


   def createTooltipBuddyData(self,buddy):
      ttime = time.strftime("%a, %d %b %Y %H:%M:%S",buddy.timestamp);
      presence = constants.C.presences[buddy.presence];
      mood = constants.C.moods[buddy.mood];
      
      # Is it a Private number
      if buddy.is_private():
         jid = _("<i>Private Number</i>");
      else:
         jid = buddy.jid;
      
      sstr = "<big><b>%s</b></big>\n" % str(buddy.name);
      sstr += "JID: <b>%s</b>\t\n" % jid;
      sstr += "%s: <b>%s</b>\n" % (_("Presence"),presence.text);
      sstr += "%s: <b>%s</b>\n" % (_("Mood"),mood.text);
      if presence.is_online():
         sstr += _(" Logged In: <b>%(time)s</b>\t\n") % {'time': ttime};
      else:
         sstr += _(" Logged Out: <b>%(time)s</b>\t\n") % {'time': ttime};

      return sstr;

   def addService(self,buddy):
      iter = self.findGroup(buddy.group);
      srvImg = gtk.gdk.pixbuf_new_from_file_at_size(iconstants.IMG_Mxit,16,16);
      
      if buddy.type == handles.BuddyType.GALLERY:
         data = (srvImg,buddy.name,None,True,
                 _("<big><b>Mxit File Service</b></big>\t\n%s\n") % buddy.name,
                 constants.C.types[buddy.type].id,buddy.jid);
      else:
         data = (srvImg,buddy.name,None,True,
                 _("<big><b>Mxit Service</b></big>\t\n%s\n") % buddy.name,
                 constants.C.types[buddy.type].id,buddy.jid);

      self.updateGroup(iter);
      self.model.get_model().append(iter,data);

   def addInvite(self,buddy):
      message = buddy.inviteMessage;

      iter = self.findGroup(self.blend.conn.roster.root_group);
      img = gtk.gdk.pixbuf_new_from_file_at_size(iconstants.IMG_Buddy,16,16);
      tooltipMsg = _("Invitation from <b>%s</b>\n") % str(buddy.name);
      if message != "":
         tooltipMsg += _("Message: ") + message + "\n";

      inviteType = constants.C.types[handles.BuddyType.INVITE].id;
      data = (img,str(buddy.name),None,True,tooltipMsg,inviteType,buddy.jid);
      self.updateGroup(iter);     
      self.model.get_model().append(iter,data);

   def addMultiMx(self,room,inviter):
      iter = self.findGroup(self.blend.conn.roster.root_group);
      img = gtk.gdk.pixbuf_new_from_file_at_size(iconstants.IMG_MultiMx,16,16);
      tooltipMsg = _("<big><b>MultiMx</b></big>\t\n Invited By: %s") % inviter;
      type = constants.C.types[handles.BuddyType.ROOM].id;
      data = (img,str(room.name),None,True,tooltipMsg,type,room.jid);
      self.updateGroup(iter);     
      self.model.get_model().append(iter,data);

   def addBuddy(self,iter,buddy):
      mood = constants.C.moods[buddy.mood];
      presence = constants.C.presences[buddy.presence];
      moodImg = gtk.gdk.pixbuf_new_from_file_at_size(mood.image,24,24);
      presImg = gtk.gdk.pixbuf_new_from_file_at_size(presence.image,16,16);

      data = (presImg,buddy.name,moodImg,True,
              self.createTooltipBuddyData(buddy),
              constants.C.types[buddy.type].id,
              buddy.jid);
      self.updateGroup(group=buddy.group);
      self.model.get_model().append(iter,data);      


   def updateBuddy(self,iter,buddy):
      mood = constants.C.moods[buddy.mood];
      presence = constants.C.presences[buddy.presence];

      j = False;
      
      if buddy.old_presence == handles.Presence.OFFLINE and buddy.presence == handles.Presence.AVAILABLE:
         # Just in
         pres = presence.jimg;
         j = True;
      else:
         pres = presence.image;
      
      if buddy.old_presence == handles.Presence.AVAILABLE and buddy.presence == handles.Presence.OFFLINE:
         # Just off
         pres = presence.jimg;
         j = True;

      moodImg = gtk.gdk.pixbuf_new_from_file_at_size(mood.image,24,24);
      presImg = gtk.gdk.pixbuf_new_from_file_at_size(pres,16,16);
      tooltip = self.createTooltipBuddyData(buddy);
      
      self.model.get_model().set_value(iter,0,presImg);
      self.model.get_model().set_value(iter,1,buddy.name.strip());
      self.model.get_model().set_value(iter,2,moodImg);
      self.model.get_model().set_value(iter,4,tooltip);
      
      self.updateGroup(group=buddy.group);
      
      if j is True:
         #print 'j true';
         gobject.timeout_add(5000,self.updatePresence,iter,buddy);

   def updatePresence(self,iter,buddy):
      presence = constants.C.presences[buddy.presence];
      presImg = gtk.gdk.pixbuf_new_from_file_at_size(presence.image,16,16);
      self.model.get_model().set_value(iter,0,presImg);
      return False;

   def updateGroup(self,iter=None,group=None):
      if iter is not None:
         groupName = self.model.get_model().get_value(iter,1);
         groupName = groupName.replace("<b>","").replace("</b>","");
         group = self.blend.conn.roster.get_group(groupName);
      elif group is not None:
         iter = self.findGroup(group);

      if group is None or iter is -1:
         return; # Can't do anything

      tooltip = self.makeTooltipString(group);
      self.model.get_model().set_value(iter,4,tooltip);

   def findGroup(self,group):
      iter = self.model.get_model().get_iter_first();
      while iter != None:
         g = self.model.get_model().get_value(iter,1);
         type = self.model.get_model().get_value(iter,5);
         if type in (const.SPECIAL_GROUP,const.UNSPECIAL_GROUP,const.GROUP):
            if g == "<b>" + group.real_name + "</b>":
               return iter;
         iter = self.model.get_model().iter_next(iter);
      return -1;

   def findBuddy(self,buddy):
      iter = self.model.get_model().get_iter_first();
      while iter != None:
         if self.model.get_model().iter_has_child(iter):
            for i in range(0,self.model.get_model().iter_n_children(iter)):
               it = self.model.get_model().iter_nth_child(iter,i);
               j = self.model.get_model().get_value(it,6);
               if j == buddy.jid:
                  return self.model.get_model().iter_nth_child(iter,i);
         else:
            j = self.model.get_model().get_value(iter,6);
            if j == buddy.jid:
               return iter;
               
         iter = self.model.get_model().iter_next(iter);
      return -1;

   # Fix this (Display the type of group)
   def makeTooltipString(self,group,type=const.GROUP):
      tooltip = "<big><b>%s</b> (%s)</big>\t\n%s:\n\t%s %s\n\t%s %s\n\t%s %s";
      return tooltip % (str(group.real_name),_("Group"),_("Contacts"),
      str(group.online),_("Online"),str(group.offline),_("Offline"),
      str(group.total),_("Total"));

   def clear(self):
      """iter = self.model.get_model().get_iter_root();
      while iter != None:
         if self.model.get_model().iter_has_child(iter):
            for i in range(0,self.model.get_model().iter_n_children(iter)):
               # Remove each child
               it = self.model.get_model().iter_nth_child(iter,i);
               if it != None:
                  self.model.get_model().remove(it);               
         self.model.get_model().remove(iter);
         iter = self.model.get_model().iter_next(iter);
      """
      self.model.get_model().clear();
      self.setInitalGroups();


   def changeMenuToLogOn(self):
      childs = self.logOffMenuItem.get_children();
      childs[0].set_text_with_mnemonic(_("_Log On"));
      logOnImage = gtk.Image();
      logOnImage.set_from_stock(gtk.STOCK_CONNECT,gtk.ICON_SIZE_MENU);     
      self.logOffMenuItem.set_image(logOnImage);
   
   def changeMenuToLogOff(self):
      childs = self.logOffMenuItem.get_children();
      childs[0].set_text_with_mnemonic(_("_Log Off"));
      logOffImage = gtk.Image();
      logOffImage.set_from_stock(gtk.STOCK_DISCONNECT,gtk.ICON_SIZE_MENU);
      self.logOffMenuItem.set_image(logOffImage);

   def listFilterFunc(self,model,iter,user_data=None):
      type = model.get_value(iter,5);
      
      if not self.blend.config.hideOfflineContacts:
         return True;

      if type == const.BUDDY:
         jid = model.get_value(iter,6);
         buddy = self.blend.conn.roster.get_buddy(jid);
         if buddy is None:
            return True;

         if buddy.presence == handles.Presence.OFFLINE:
            # Hide
            return False;

      return True;

   def listSortFunc(self,model,iterA,iterB,data):
      # We always sort acending
      # -1 if iterA must go first
      # 0 if equal
      # 1 if iterB must go first
      nameA = model.get_value(iterA,1).replace("<b>","").replace("</b>","");
      try:
         nameB = model.get_value(iterB,1).replace("<b>","").replace("</b>","");
      except AttributeError:
         # The iter doesn't really exist for some arb reason
         return 0;
      
      if model.get_value(iterA,5) == const.SPECIAL_GROUP:
         # BlendIT. Must go to top
         return -1;
          
      if model.get_value(iterB,5) == const.SPECIAL_GROUP:
         # BlendIt. Must go to top
         return 1;

      if model.get_value(iterA,5) == const.UNSPECIAL_GROUP:
         # MXit Services. Must go down
         return 1;

      if model.get_value(iterB,5) == const.UNSPECIAL_GROUP:
         # MXit Services. Must go down
         return -1;
      
      if nameA.lower() < nameB.lower():
         return -1;
      
      if nameA.lower() == nameB.lower():
         return 0;
      
      if nameA.lower() > nameB.lower():
         return 1;
      
      return 0;


   ### Status Bar stuff ###
   def drawStatusBar(self):
      hbox = gtk.HBox();
      hbox.pack_start(self.drawStatusSelector(),True,True);
      hbox.pack_end(self.drawMoodSelector(),True,True);
      hbox.show();
      
      return hbox;

   def createMoods(self,store):
      moods = constants.C.moods.values();
      moods.sort(key=self._alphabetise);

      for i in range(0,len(moods)):
         img = gtk.gdk.pixbuf_new_from_file(moods[i].image);
         store.append((img,moods[i].text,moods[i].int));

   def _alphabetise(self,mood):
      return mood.sort.lower();

   def drawMoodSelector(self):
      # Image, Mood Text, constant as int
      self.moodListstore = gtk.ListStore(gtk.gdk.Pixbuf,str,int)
      self.createMoods(self.moodListstore);
      self.moodBox = gtk.ComboBox(self.moodListstore);

      icon = gtk.CellRendererPixbuf();
      self.moodBox.pack_start(icon,False);
      self.moodBox.add_attribute(icon,'pixbuf',0);
      
      status = gtk.CellRendererText();
      self.moodBox.pack_start(status,True);
      self.moodBox.add_attribute(status,'text',1);

      self.moodBox.set_active(0);
      self.moodBox.set_wrap_width(3);
      self.moodBoxChangeHandler = self.moodBox.connect('changed',self.sigs.on_moodBox_change);
      self.moodBox.show();
      
      return self.moodBox;


   def removeTempStatus(self):
      removeIters = [];
      for i in range(0,len(self.statusListStore)):
         itr = self.statusListStore[str(i)];
         iter = itr.iter;
      
         if self.statusListStore.get_value(iter,2) == -1:
            removeIters.append(iter);
         elif self.statusListStore.get_value(iter,2) == 1:
            onlineIter = iter;
            
      for i in range(0,len(removeIters)):
         self.statusListStore.remove(removeIters[i]);

      self.statusBox.set_active_iter(onlineIter);
      self.statusBox.set_sensitive(True);
   
   def addConnectingStatus(self,message):
      iter = self.statusListStore.get_iter(0);
      if self.statusListStore.get_value(iter,2) == -1:
         self.changeConnectingStatus(message);

      connectingImg = gtk.gdk.pixbuf_new_from_file(iconstants.IMG_Connecting);
      self.statusListStore.prepend((connectingImg,message,-1));
      self.statusBox.set_active(0);
      self.statusBox.set_sensitive(False);

   def changeConnectingStatus(self,message):
      iter = self.statusListStore.get_iter(0);
      self.statusListStore.set(iter,1,message);

   def createStatuses(self,store):
      statuses = constants.C.orderedPresences;
      for i in range(0,len(statuses)):
         image = gtk.gdk.pixbuf_new_from_file(statuses[i].image);
         store.append((image,statuses[i].text,statuses[i].int));

   def drawStatusSelector(self):
      # Image, Text, constant as int
      self.statusListStore = gtk.ListStore(gtk.gdk.Pixbuf,str,int)
      self.createStatuses(self.statusListStore);
      self.statusBox = gtk.ComboBox(self.statusListStore);

      icon = gtk.CellRendererPixbuf();
      self.statusBox.pack_start(icon,False);
      self.statusBox.add_attribute(icon,'pixbuf',0);
      
      status = gtk.CellRendererText();
      self.statusBox.pack_start(status,True);
      self.statusBox.add_attribute(status,'text',1);


      self.statusBox.set_active(1);
      self.statusBoxChangeHandler = self.statusBox.connect('changed',self.sigs.on_statusBox_change);
      self.statusBox.show();
      
      return self.statusBox;


   ### Treeview Code ###
   def createGroupPopupMenu(self,menu,disabled=False):
      addContactItem = gtk.ImageMenuItem(_("_Add new Buddy"));
      addContactImage = gtk.Image();
      addContactImage.set_from_stock(gtk.STOCK_ADD,gtk.ICON_SIZE_MENU);
      addContactItem.set_image(addContactImage);
      addContactItem.connect('activate',self.sigs.on_add_contact,True);
      menu.add(addContactItem);

      renameGroupItem = gtk.ImageMenuItem(_("_Rename Group"));
      renameGroupImage = gtk.Image();
      renameGroupImage.set_from_stock(gtk.STOCK_EDIT,gtk.ICON_SIZE_MENU);
      renameGroupItem.set_image(renameGroupImage);
      if disabled == True:
         renameGroupItem.set_sensitive(False);
      menu.add(renameGroupItem);

      deleteGroupItem = gtk.ImageMenuItem(_("_Delete Group"));
      deleteGroupImage = gtk.Image();
      deleteGroupImage.set_from_stock(gtk.STOCK_REMOVE,gtk.ICON_SIZE_MENU);
      deleteGroupItem.set_image(deleteGroupImage);
      if disabled == True:
         deleteGroupItem.set_sensitive(False);
      menu.add(deleteGroupItem);
      
      # Menu Separator
      sep = gtk.SeparatorMenuItem();
      sep.show();
      menu.add(sep);
      
      # Broadcast message
      broadcastGroupItem = gtk.ImageMenuItem(_("_Broadcast Message"));
      broadcastGroupImage = gtk.Image();
      broadcastGroupImage.set_from_file(iconstants.IMG_Broadcast);
      broadcastGroupItem.set_image(broadcastGroupImage);
      broadcastGroupItem.connect('activate',self.sigs.broadcast_message);
      menu.add(broadcastGroupItem);


   def createInvitePopupMenu(self,menu,disabled=False):
      addContactItem = gtk.ImageMenuItem(_("_Accept Invite"));
      addContactImage = gtk.Image();
      addContactImage.set_from_stock(gtk.STOCK_APPLY,gtk.ICON_SIZE_MENU);
      addContactItem.set_image(addContactImage);
      addContactItem.connect('activate',self.sigs.accept_invite);
      menu.add(addContactItem);

      declineContactItem = gtk.ImageMenuItem(_("_Decline Invite"));
      declineContactImage = gtk.Image();
      declineContactImage.set_from_stock(gtk.STOCK_CANCEL,gtk.ICON_SIZE_MENU);
      declineContactItem.set_image(declineContactImage);
      declineContactItem.connect('activate',self.sigs.reject_invite);
      if disabled == True:
         declineContactItem.set_sensitive(False);
      menu.add(declineContactItem);

      blockContactItem = gtk.ImageMenuItem(_("_Block Contact"));
      blockContactImage = gtk.Image();
      blockContactImage.set_from_stock(gtk.STOCK_DIALOG_ERROR,gtk.ICON_SIZE_MENU);
      blockContactItem.set_image(blockContactImage);
      blockContactItem.connect('activate',self.sigs.block_contact);
      if disabled == True:
         blockContactItem.set_sensitive(False);
      menu.add(blockContactItem);



   def createBuddyPopupMenu(self,menu,iter):
      imContactItem = gtk.ImageMenuItem(_("_Send Message"));
      imContactImage = gtk.Image();
      imContactImage.set_from_stock(gtk.STOCK_NEW,gtk.ICON_SIZE_MENU);
      imContactItem.set_image(imContactImage);
      imContactItem.connect('activate',self.sigs.on_rightclick_send_message);
      menu.add(imContactItem);

      separator1 = gtk.SeparatorMenuItem();
      menu.add(separator1);

      reinviteContactItem = gtk.ImageMenuItem(_("_Reinvite"));
      reinviteContactImage = gtk.Image();
      reinviteContactImage.set_from_stock(gtk.STOCK_REDO,gtk.ICON_SIZE_MENU);
      reinviteContactItem.set_image(reinviteContactImage);
      reinviteContactItem.connect('activate',self.sigs.on_reinvite_contact);
      menu.add(reinviteContactItem);

      removeContactItem = gtk.ImageMenuItem(_("_Remove Contact"));
      removeContactImage = gtk.Image();
      removeContactImage.set_from_stock(gtk.STOCK_REMOVE,gtk.ICON_SIZE_MENU);
      removeContactItem.set_image(removeContactImage);
      removeContactItem.connect('activate',self.sigs.on_remove_contact);
      menu.add(removeContactItem);


   def createMultiMxMenu(self,menu,iter):
      inviteContactsItem = gtk.ImageMenuItem(_("_Invite Contacts"));
      inviteContactsImage = gtk.Image();
      inviteContactsImage.set_from_stock(gtk.STOCK_ADD,gtk.ICON_SIZE_MENU);
      inviteContactsItem.set_image(inviteContactsImage);
      inviteContactsItem.connect('activate',self.sigs.on_rightclick_inviteMMx);
      menu.add(inviteContactsItem);
      
      leaveRoomItem = gtk.ImageMenuItem(_("_Leave Room"));
      leaveRoomImage = gtk.Image();
      leaveRoomImage.set_from_stock(gtk.STOCK_CLOSE,gtk.ICON_SIZE_MENU);
      leaveRoomItem.set_image(leaveRoomImage);
      leaveRoomItem.connect('activate',self.sigs.on_rightclick_closeMMx);
      menu.add(leaveRoomItem);


   def displayTreePopupMenu(self,path,col,button,time):
      popup = gtk.Menu();

      # We must find the data that tells us what type we are:
      iter = self.model.get_model().get_iter(path);
      type = self.model.get_model().get_value(iter,5);
      if type == const.GROUP:
         self.createGroupPopupMenu(popup);
      elif type == const.BUDDY:
         self.createBuddyPopupMenu(popup,iter);
      elif type == const.INVITE:
         self.createInvitePopupMenu(popup);
      elif type == const.SPECIAL_GROUP:
         self.createGroupPopupMenu(popup,True);
      elif type == const.ROOM:
         self.createMultiMxMenu(popup,iter);      

      # Special and Unspecial Group don't have popup menus
      if type == const.SERVICE or type == const.UNSPECIAL_GROUP:
         return

      popup.show_all();
      popup.popup(None,None,None,button,time);


   
   def drawScrolledTreeView(self):
      self.tree = gtk.TreeView();
      self.createTreeModel();     
      self.tree.set_model(self.model);
      self.tree.set_reorderable(True);
      drag = [('buddy',0,0)];
      self.tree.enable_model_drag_dest(drag,gtk.gdk.ACTION_COPY);
      self.tree.enable_model_drag_source(gtk.gdk.BUTTON1_MASK,drag,
                                         gtk.gdk.ACTION_COPY);
      #self.tree.connect('drag-data-received',self.sigs.on_buddy_drag_data);
      #self.tree.connect('drag-data-get',self.sigs.on_buddy_drag_get);
      self.tree.connect('drag-drop',self.sigs.on_buddy_drag);

      ## CellRenderers
      # Status
      status = gtk.TreeViewColumn(_("Status"));
      self.tree.append_column(status);
      statusCell = gtk.CellRendererPixbuf();
      status.pack_start(statusCell,False);
      status.add_attribute(statusCell,'pixbuf',0);
      
      nickCell = gtk.CellRendererText();
      nickCell.set_property('editable',3);
      nickname = gtk.TreeViewColumn(_("Nickname"),nickCell,markup=1); #,editable=3
      nickname.set_expand(True);
      nickCell.connect('edited',self.sigs.on_buddyList_edited);
      self.tree.append_column(nickname);
      
      # Mood
      mood = gtk.TreeViewColumn(_("Mood"));
      self.tree.append_column(mood);
      moodCell = gtk.CellRendererPixbuf();
      mood.pack_start(moodCell,False);
      mood.add_attribute(moodCell,'pixbuf',2);

      # More tree options
      self.model.get_model().set_sort_column_id(1,gtk.SORT_ASCENDING);
      self.model.get_model().set_sort_func(1,self.listSortFunc,None);
      self.tree.set_search_column(1);
      self.tree.set_tooltip_column(4);
      self.tree.set_headers_visible(False);
      self.tree.set_enable_search(True);
      self.tree.set_show_expanders(True);
      self.tree.set_level_indentation(-16);
      # Some signals:
      self.tree.add_events(gtk.gdk.BUTTON_PRESS_MASK);
      self.tree.connect('button_press_event',self.sigs.on_buddyList_press_event);
            
      self.tree.show();
      
      # Put the treeview into the scrolled window
      # so the user can scroll down if he has lotsa
      # contacts.
      scrollWindow = gtk.ScrolledWindow();
      scrollWindow.set_policy(gtk.POLICY_NEVER,gtk.POLICY_AUTOMATIC);
      scrollWindow.add(self.tree);
      scrollWindow.show();
      
      return scrollWindow;



   def createTreeModel(self):
      # MODEL IS THE FOLLOWING:
      # Presence (Image), Display Name (String), Mood (Image),
      # Deprecated (boolean), Tooltip, Type, JID (String)
      self.modelA = gtk.TreeStore(gtk.gdk.Pixbuf,str,gtk.gdk.Pixbuf,
                                  str,str,int,str);
      self.model = self.modelA.filter_new();
      self.model.set_visible_func(self.listFilterFunc);
      self.setInitalGroups();


   def setInitalGroups(self):
      noImg = gtk.gdk.pixbuf_new_from_file_at_size(iconstants.IMG_Blank,16,16);
      self.model.get_model().append(None,(noImg,
                              "<b>BlendIT</b>",
                              None,
                              False,
                              "",
                              const.SPECIAL_GROUP,
                              ""));

      self.model.get_model().append(None,(None,
                              "<b>MXit Services</b>",
                              None,
                              False,
                              "",
                              const.UNSPECIAL_GROUP,
                              ""));


   ### Menu Bar Code ###
   def drawAccountMenuList(self,accel_group):
      separator = gtk.SeparatorMenuItem();
      separator.show();
      
      editAccountMenuItem = gtk.ImageMenuItem(_("_Edit Account"));
      editAccountImage = gtk.Image();
      editAccountImage.set_from_stock(gtk.STOCK_EDIT,gtk.ICON_SIZE_MENU);
      editAccountMenuItem.set_image(editAccountImage);
      editAccountMenuItem.connect("activate",self.sigs.on_edit_own_account);
      editAccountMenuItem.show();

      self.logOffMenuItem = gtk.ImageMenuItem(_("_Log Off"));
      logOffImage = gtk.Image();
      logOffImage.set_from_stock(gtk.STOCK_DISCONNECT,gtk.ICON_SIZE_MENU);
      self.logOffMenuItem.set_image(logOffImage);
      self.logOffMenuItem.connect("activate",self.sigs.on_logoff,True);
      self.logOffMenuItem.add_accelerator("activate", accel_group,ord('L'),gtk.gdk.CONTROL_MASK,gtk.ACCEL_VISIBLE);
      self.logOffMenuItem.show();
      
      quitMenuItem = gtk.ImageMenuItem(_("_Quit"));
      quitImage = gtk.Image();
      quitImage.set_from_stock(gtk.STOCK_QUIT,gtk.ICON_SIZE_MENU);
      quitMenuItem.set_image(quitImage);
      quitMenuItem.connect("activate",self.csigs.on_quit);
      quitMenuItem.add_accelerator("activate", accel_group,ord('Q'),gtk.gdk.CONTROL_MASK,gtk.ACCEL_VISIBLE);
      quitMenuItem.show();
      
      accountSubmenu = gtk.Menu();
      accountSubmenu.append(editAccountMenuItem);
      accountSubmenu.append(separator);
      accountSubmenu.append(self.logOffMenuItem);
      accountSubmenu.append(quitMenuItem);
      accountSubmenu.show();
      accountList = gtk.MenuItem(_("Accounts"));
      accountList.set_submenu(accountSubmenu);
      accountList.show();
      
      return accountList;



   def drawContactsMenuList(self,accel_group):
      self.hideOffLineContactsItem = gtk.CheckMenuItem(_("_Hide Offline Contacts"));
      if self.blend.config.hideOfflineContacts == True:
         self.hideOffLineContactsItem.set_active(True);
      self.hideOffLineContactsItem.connect("activate",self.sigs.on_hide_contacts);
      self.hideOffLineContactsItem.add_accelerator("activate", accel_group,ord('H'),gtk.gdk.CONTROL_MASK,gtk.ACCEL_VISIBLE);
      self.hideOffLineContactsItem.show();
      
      separator = gtk.SeparatorMenuItem();
      separator.show();

      newMultiMxItem = gtk.ImageMenuItem(_("_New MultiMx"));
      newMultiMxImage = gtk.Image();
      newMultiMxImage.set_from_file(iconstants.IMG_MultiMx);
      newMultiMxItem.set_image(newMultiMxImage);
      newMultiMxItem.connect("activate",self.csigs.on_new_multimx);
      newMultiMxItem.add_accelerator("activate", accel_group,ord('M'),gtk.gdk.CONTROL_MASK,gtk.ACCEL_VISIBLE);
      newMultiMxItem.show();

      addContactItem = gtk.ImageMenuItem(_("_Add Contact"));
      addContactImage = gtk.Image();
      addContactImage.set_from_file(iconstants.IMG_Buddy);
      addContactItem.set_image(addContactImage);
      addContactItem.connect("activate",self.sigs.on_add_contact);
      addContactItem.add_accelerator("activate", accel_group,ord('N'),gtk.gdk.CONTROL_MASK,gtk.ACCEL_VISIBLE);
      addContactItem.show();

      createGroupItem = gtk.ImageMenuItem(_("_Create Group"));
      createGroupImage = gtk.Image();
      createGroupImage.set_from_file(iconstants.IMG_Group);
      createGroupItem.set_image(createGroupImage);
      createGroupItem.connect("activate",self.sigs.on_create_group);
      createGroupItem.show();

      contactSubmenu = gtk.Menu();
      contactSubmenu.append(newMultiMxItem);
      contactSubmenu.append(addContactItem);
      contactSubmenu.append(createGroupItem);
      contactSubmenu.append(separator);
      contactSubmenu.append(self.hideOffLineContactsItem);
      contactSubmenu.show();
      contactList = gtk.MenuItem(_("Contacts"));
      contactList.set_submenu(contactSubmenu);
      contactList.show();
      
      return contactList;



   def drawToolsMenuList(self,accel):
      preferencesItem = gtk.ImageMenuItem(_("_Preferences"));
      preferencesImage = gtk.Image();
      preferencesImage.set_from_stock(gtk.STOCK_PREFERENCES,gtk.ICON_SIZE_MENU);
      preferencesItem.set_image(preferencesImage);
      preferencesItem.connect("activate",self.sigs.on_preferences);
      preferencesItem.show();

      debugItem = gtk.ImageMenuItem(_("_Debug Console"));
      debugImage = gtk.Image();
      debugImage.set_from_stock(gtk.STOCK_EXECUTE,gtk.ICON_SIZE_MENU);
      debugItem.set_image(debugImage);
      debugItem.connect("activate",self.sigs.on_debug_console);
      debugItem.show();

      toolsSubmenu = gtk.Menu();
      toolsSubmenu.append(preferencesItem);
      toolsSubmenu.append(debugItem);
      toolsSubmenu.show();
      toolsList = gtk.MenuItem(_("Tools"));
      toolsList.set_submenu(toolsSubmenu);
      toolsList.show();
      
      return toolsList;

   
   def drawMenuBar(self,accel):
      menu = gtk.MenuBar();
      menu.append(self.drawAccountMenuList(accel));
      menu.append(self.drawContactsMenuList(accel));
      menu.append(self.drawToolsMenuList(accel));
      menu.show();
      
      return menu;